<?php
define('SAE_MYSQL_HOST_M',"localhost");
define('SAE_MYSQL_USER',"root");
define('SAE_MYSQL_PASS',"demhghc");
define('SAE_MYSQL_PORT',"3306");
define('SAE_MYSQL_DB',"zthubo");
define('REDIS_PASS',"Af1121113");
class KVtemp {
	public $Table, $db, $EnCrypt, $password;
	function __construct() {
		$this->Table = "data"; //K-V键值对储存的表
		$this->EnCrypt = C('KV_EnCrypt'); //是否加密内容
		$this->password = C('USER_AUTH_KEY'); //加密内容用密钥
		$this->db = new SQLite3(C('Sqlite_path'));
        //$this->db->open(C('Sqlite_path'));
		//$this->db->set_charset("utf8");

	}
    public function init(){
        if($this->db->querySingle('SELECT * FROM sqlite_master WHERE name="KV_'.$this->Table.'"')==null){
            $this->db->exec('CREATE TABLE KV_'.$this->Table.' (K text NOT NULL , V text,PRIMARY KEY (K))');
        }
    }
    public function set($K,$V){
        
        if(C('KV_EnCrypt')){
            $val=UrlBase64Encode(EnCrypt(json_encode($V),$this->password));
        }else{
            $val=json_encode($V);
        }
        //$val=$this->EnCrypt?UrlBase64Encode(EnCrypt(json_encode($V),$this->password)):json_encode($V);
        if(count($this->db->querySingle("SELECT * FROM 'KV_{$this->Table}' WHERE K='{$K}'",true))==0){
            $sql="INSERT INTO 'KV_{$this->Table}' (K,V) VALUES ('{$K}','{$val}')";   
        }else{
            $sql="UPDATE 'KV_{$this->Table}' SET V= '{$val}' WHERE (K = '{$K}')";
        }
        $this->db->exec($sql);
    }
    public function get($K){
        $val=$this->db->querySingle("SELECT * FROM 'KV_{$this->Table}' WHERE K='{$K}'",true);
        if(count($val)==0){
            $re=null;
        }else{
            if($this->EnCrypt){
                $re=json_decode(DeCrypt(UrlBase64Decode($val['V']),$this->password)); 
            }else{
                $re=json_decode($val['V']); 
            } 
        }
        return $re;
    }
}
class SaeKV extends KVtemp{

}
?>
